# -*- coding: utf-8 -*-

"""
.. todo:: docstring
.. todo:: make the relative import failure a warning?

"""

import logging

# Versioning scheme based on: http://en.wikipedia.org/wiki/Versioning#Designating_development_stage
#
#   +-- api change, probably incompatible with older versions
#   |     +-- enhancements but no api change
#   |     |
# major.minor[.build[.revision]]
#                |
#                +-|* 0 for alpha (status)
#                  |* 1 for beta (status)
#                  |* 2 for release candidate
#                  |* 3 for (public) release
#
# For instance:
#     * 1.2.0.1 instead of 1.2-a
#     * 1.2.1.2 instead of 1.2-b2 (beta with some bug fixes)
#     * 1.2.2.3 instead of 1.2-rc (release candidate)
#     * 1.2.3.0 instead of 1.2-r (commercial distribution)
#     * 1.2.3.5 instead of 1.2-r5 (commercial distribution with many bug fixes)

__version__ = "0.0.0.0"
__author__ = "DR0ID (C) 2011"

__copyright__ = "Copyright 2011, pyknicpygame"
__credits__ = ["DR0ID"]
__license__ = "GPL3"
__maintainer__ = "DR0ID"

__all__ = ["context", "pyknic", "transform", "spritesystem"]


# import pyknic, either relative of absolute
try:
    from . import pyknic
except ImportError as e:
    if __debug__:
        debug_logger = logging.getLogger('pyknicpygame')
        handler = logging.StreamHandler()
        debug_logger.addHandler(handler)
        debug_logger.error('IMPORT: relative import failed, trying absolute import! ' + str(e))
        import sys
        import traceback
        # import StringIO
        try:
            # python 2.x
            import StringIO
            from StringIO import StringIO
            exc_traceback = sys.exc_traceback
        except:
            # python 3.x
            from io import StringIO
            exc_type, exc_value, exc_traceback = sys.exc_info()
        strIO = StringIO()
        traceback.print_tb(exc_traceback, None, strIO)
        debug_logger.debug(strIO.getvalue())
        debug_logger.handlers.remove(handler) # remove it again to not mess up real setup
    import pyknic

# -----------------------------------------------------------------------------
# shortcut for pyknic.settings
settings = pyknic.settings

# add pyknicpygame specific settings
pyknic.settings['resolution'] = (800, 600)
pyknic.settings['log_level'] = logging.DEBUG if __debug__ else logging.INFO
pyknic.settings['log_to_console'] = True if __debug__ else False

# -----------------------------------------------------------------------------


# -----------------------------------------------------------------------------
# check pygame version
import pygame
pyknic.check_version((1, 9, 3), pygame.version.vernum, (1, 9, 0))

# check pyknic version
pyknic.check_version((4, 0, 0, 0), pyknic.info.version_info, (3, 0, 0, 0))

# -----------------------------------------------------------------------------

def _set_up_logging():
    """
    Sets up a basic logging configuration.

    .. todo:: explain logging options (maybe in settings?) and how it works
    """
    logger = logging.getLogger("pyknicpygame")
    if not settings['log_to_file'] and not settings['log_to_console']:
        null_handler = pyknic.NullHandler()
        logger.addHandler(null_handler)

    if settings['log_to_file']:
        for handler in logging.getLogger('pyknic').handlers:
            if isinstance(handler, logging.handlers.RotatingFileHandler):
                logger.addHandler(handler)


    if 'log_console_handler' in settings and settings['log_console_handler'] is not None:
        logger.addHandler(settings['log_console_handler'])

# -----------------------------------------------------------------------------

# read only
is_initialized = False

def init():
    global is_initialized
    if not is_initialized:
        is_initialized = True

        _set_up_logging()

        pyknic.init()

        _logger = logging.getLogger('pyknicpygame')
        _logger.info("**************************************************")
        _logger.info("%-50s" % ("pyknicpygame v" + str(__version__) + \
                                                        " (c) DR0ID 2011"))
        _logger.info("**************************************************")

        _logger.info("using pygame version: " + str(pygame.version.ver) + \
                                " (SDL: " + str(pygame.get_sdl_version()) + ")")


        #local imports
        from . import context
        from . import transform
        from . import spritesystem

    else:
        logging.warn("pyknicpygame already initialized, should only called once")
# -----------------------------------------------------------------------------
